package net.zjitc.listthree.web;

import net.zjitc.listthree.domin.User;
import net.zjitc.listthree.service.UserService;
import net.zjitc.listthree.service.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

/**
 * @Author Administrator
 * @Date 2020/6/18 16:45
 * 表示层的控制器Servlet
 * 作用：
 * 1.获取请求参数
 * 2.需要的话，将参数封装
 * 3.调用service层相应方法完成功能（可能需要传递参数）
 * 4.需要的话，将结果保存在域对象（供视图jsp展示数据）
 * 5.转发或重定向到另一个Jsp/servlet
 **/
@WebServlet("/addUser")
public class AddUser extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /*1.设置请求编码
        * 2.获取所有请求参数
        * 3.将请求参数封装到User对象
        * 4.调用service层返回完成添加用户功能
        *5. 根据返回值决定：
        * 转发到add.jsp或重定向userList
        **/
        request.setCharacterEncoding("utf-8");
        Map<String,String[]> map = request.getParameterMap();
        User user = new User();
        try {
            /*自动将map对象封装为user对象*/
            BeanUtils.populate(user,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        UserService service=new UserServiceImpl();
        int i=service.addUser(user);
        if (i>0){
            response.sendRedirect(request.getContextPath()+"/userList");
        }else if (i==0){
            request.setAttribute("add_error","添加失败");
            request.getRequestDispatcher("/listthree/add.jsp").forward(request,response);
        }else {
            request.setAttribute("add_error","用户名不能重复");
            request.getRequestDispatcher("/listthree/add.jsp").forward(request,response);
        }
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}
